package info.gridworld.grid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SparseBoundedGrid2<E> extends AbstractGrid<E> {
    Map<Location, E> occMap = new HashMap();
    int nRows;
    int nCols;

    public SparseBoundedGrid2(int nRows, int nCols) {
        if (nRows <= 0)
            throw new IllegalArgumentException("rows <= 0");
        if (nCols <= 0)
            throw new IllegalArgumentException("cols <= 0");
        this.nRows = nRows;
        this.nCols = nCols;
    }

    @Override
    public int getNumRows() {
        return this.nRows;
    }

    @Override
    public int getNumCols() {
        return this.nCols;
    }

    @Override
    public boolean isValid(Location loc) {
        return 0 <= loc.getRow() && loc.getRow() < getNumRows()
                && 0 <= loc.getCol() && loc.getCol() < getNumCols();
    }

    @Override
    public E put(Location loc, E obj) {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc + " is not valid");
        if (obj == null)
            throw new NullPointerException("obj == null");

        return this.occMap.put(loc, obj);

    }

    @Override
    public E remove(Location loc) {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");

        return this.occMap.remove(loc);
    }

    @Override
    public E get(Location loc) {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc + " is not valid");

        return this.occMap.get(loc);
    }

    @Override
    public ArrayList<Location> getOccupiedLocations() {
        ArrayList<Location> theLocations = new ArrayList<Location>();

        for (Location loc : this.occMap.keySet())
            theLocations.add(loc);
        return theLocations;
    }
}
